<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>个人资料 - 网上跳蚤市场</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" th:href="@{/css/style.css}" />
</head>
<body>
<div th:replace="layout :: .nav"></div>
<div class="container">
    <section class="fade-in">
        <h2>个人资料</h2>
        <div id="profileInfo" class="card">
            <p>加载中...</p>
        </div>

        <div class="card mt-20">
            <h3>修改个人信息</h3>
            <form id="profileForm">
                <div class="form-group">
                    <label for="username">用户名:</label>
                    <input type="text" id="username" name="username" placeholder="请输入用户名">
                </div>
                <div class="form-group">
                    <label for="phoneNumber">电话号码:</label>
                    <input type="text" id="phoneNumber" name="phoneNumber" placeholder="请输入电话号码">
                </div>
                <button type="submit" class="btn">保存</button>
            </form>
        </div>

        <div class="card mt-20">
            <h3>修改密码</h3>
            <form id="passwordForm">
                <div class="form-group">
                    <label for="oldPassword">原密码:</label>
                    <input type="password" id="oldPassword" name="oldPassword" required>
                </div>
                <div class="form-group">
                    <label for="newPassword">新密码:</label>
                    <input type="password" id="newPassword" name="newPassword" required>
                </div>
                <div class="form-group">
                    <label for="confirmPassword">确认密码:</label>
                    <input type="password" id="confirmPassword" name="confirmPassword" required>
                </div>
                <button type="submit" class="btn">修改密码</button>
            </form>
        </div>

        <div id="msg" class="mt-20"></div>
    </section>
</div>

<script>
    // 加载用户信息
    async function loadUserProfile() {
        try {
            const res = await fetch('/api/users/me', {
                credentials: 'include'
            });

            if (res.status === 403 || res.status === 401) {
                window.location.href = '/login';
                return;
            }

            const user = await res.json();

            if (!user || !user.id) {
                document.getElementById('profileInfo').innerHTML = '<p>请先登录</p>';
                return;
            }

            // 显示用户信息
            let html = `
            <p><strong>用户名:</strong> ${user.username}</p>
            <p><strong>角色:</strong> ${user.role === 'admin' ? '管理员' :
                user.role === 'categoryAdmin' ? '分类管理员' :
                    user.role === 'user' ? '普通用户' : '游客'}</p>
            <p><strong>电话号码:</strong> ${user.phoneNumber || '未设置'}</p>
        `;

            document.getElementById('profileInfo').innerHTML = html;

            // 填充表单
            document.getElementById('username').value = user.username || '';
            document.getElementById('phoneNumber').value = user.phoneNumber || '';

        } catch (e) {
            console.error('加载用户信息失败:', e);
            document.getElementById('profileInfo').innerHTML = '<p class="error-msg">加载用户信息失败</p>';
        }
    }

    // 修改个人信息
    document.getElementById('profileForm').onsubmit = async function(e) {
        e.preventDefault();

        const username = document.getElementById('username').value;
        const phoneNumber = document.getElementById('phoneNumber').value;

        try {
            document.getElementById('msg').innerHTML = '<div class="info-msg">正在更新个人信息...</div>';

            const res = await fetch('/api/users/update-profile', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
                body: JSON.stringify({ username, phoneNumber })
            });

            const data = await res.json();

            if (data.success) {
                document.getElementById('msg').innerHTML = '<div class="success-msg">个人信息更新成功</div>';
                // 重新加载用户信息
                loadUserProfile();

                // 2秒后清除消息
                setTimeout(() => {
                    document.getElementById('msg').innerHTML = '';
                }, 2000);
            } else {
                document.getElementById('msg').innerHTML = `<div class="error-msg">${data.error || '更新失败'}</div>`;

                // 3秒后清除错误消息
                setTimeout(() => {
                    document.getElementById('msg').innerHTML = '';
                }, 3000);
            }
        } catch (e) {
            console.error('更新个人信息失败:', e);
            document.getElementById('msg').innerHTML = '<div class="error-msg">更新个人信息失败</div>';

            // 3秒后清除错误消息
            setTimeout(() => {
                document.getElementById('msg').innerHTML = '';
            }, 3000);
        }
    };

    // 修改密码
    document.getElementById('passwordForm').onsubmit = async function(e) {
        e.preventDefault();

        const oldPassword = document.getElementById('oldPassword').value;
        const newPassword = document.getElementById('newPassword').value;
        const confirmPassword = document.getElementById('confirmPassword').value;

        if (newPassword !== confirmPassword) {
            document.getElementById('msg').innerHTML = '<div class="error-msg">新密码与确认密码不匹配</div>';
            return;
        }

        try {
            document.getElementById('msg').innerHTML = '<div class="info-msg">正在修改密码...</div>';

            const res = await fetch('/api/users/update-password', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
                body: JSON.stringify({ oldPassword, newPassword, confirmPassword })
            });

            const data = await res.json();

            if (data.msg) {
                document.getElementById('msg').innerHTML = `<div class="success-msg">${data.msg}</div>`;
                // 清空密码表单
                document.getElementById('passwordForm').reset();
            } else {
                document.getElementById('msg').innerHTML = `<div class="error-msg">${data.error || '修改密码失败'}</div>`;
            }
        } catch (e) {
            console.error('修改密码失败:', e);
            document.getElementById('msg').innerHTML = '<div class="error-msg">修改密码失败</div>';
        }
    };

    // 页面加载时获取用户信息
    loadUserProfile();
</script>
</body>
</html>